import asyncio
import websockets
from plane_sim import *

IP_ADDR = "127.0.0.1"
IP_PORT = 19910

PLAN_NUM = 1000

# 目标模拟
pos = SimPos(lat=37,lon=121,alt=10000)
sim = SimAirline(PLAN_NUM, pos)
sim.start()

# 握手，不是必须，通过接收的 hello，发送“123”来进行双方的握手
async def serverHands(websocket):
    while True:
        recv_text = await websocket.recv()
        print("recv_text" + recv_text)
        if recv_text == "hello":
            print("connected success")
            await websocket.send("123")
            return True
        else:
            await websocket.send("connected fail")

# 接收从客户端发来的消息并处理，再返给客户端ok
async def serverRecv(websocket):
    while True:
        recv_text = await websocket.recv()
        print("recv: ", recv_text)
        await websocket.send("ok!!!")

# 握手并接收数据
async def serverRun(websocket, path):
    # await serverHands(websocket)
    # await serverRecv(websocket)
    while True:
        await asyncio.sleep(1)
        data = sim.get_json()
        await websocket.send(data)
        # print(data)
        print(int(time.time()))

start_server = websockets.serve(serverRun, IP_ADDR, IP_PORT)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
